from rest_framework import serializers
from rest_framework.exceptions import APIException

from patient.models import PatientInfo, Home, HospitalInfo
from user.models import Doctor


class PatientSerializer(serializers.ModelSerializer):
    class Meta:
        model = PatientInfo
        fields = ['id', 'name', 'gender', 'data_birth', 'mobile', 'blood', 'family_mobile', 'doctor',
                  'doctor_name', 'department', 'department_info', 'result', 'result_info', 'gender_name', ]

    gender_name = serializers.SerializerMethodField(read_only=True)

    def get_gender_name(self, obj):
        return obj.get_gender_display()

    doctor_name = serializers.SerializerMethodField(read_only=True)

    def get_doctor_name(self, obj):
        return obj.doctor.name

    department_info = serializers.SerializerMethodField(read_only=True)

    def get_department_info(self, obj):
        return obj.department.name

    result_info = serializers.SerializerMethodField(read_only=True)

    def get_result_info(self, obj):
        return obj.result.result_content


class HospitalInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = HospitalInfo
        fields = '__all__'


class DoctorNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Doctor
        fields = ['id', 'name']


class CreateRoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Home
        fields = '__all__'


class GetHospitalSerializer(serializers.ModelSerializer):
    class Meta:
        model = HospitalInfo
        fields = ['id', 'name', 'gender_name', 'data_birth', 'mobile', 'patient_id', 'blood', 'department_name',
                  'result', 'doctor_name', 'hospital_time', 'time_length', 'ward_code', 'ward_number', 'ward_type', ]

    gender_name = serializers.SerializerMethodField(read_only=True)

    def get_gender_name(self, obj):
        return obj.get_gender_display()

    ward_code = serializers.SerializerMethodField(read_only=True)

    def get_ward_code(self, obj):
        return obj.ward.ward_code

    ward_number = serializers.SerializerMethodField(read_only=True)

    def get_ward_number(self, obj):
        return obj.ward.ward_number

    ward_type = serializers.SerializerMethodField(read_only=True)

    def get_ward_type(self, obj):
        return obj.ward.get_ward_type_display()


# 药品开单的序列化
class QueryUserSerializer(serializers.ModelSerializer):
    mobile = serializers.CharField()

    class Meta:
        model = HospitalInfo
        fields = ['name', 'mobile']

    def validate(self, attrs):
        name = attrs.get('name')
        mobile = attrs.get('mobile')
        try:
            HospitalInfo.objects.get(name=name, mobile=mobile)
            return attrs
        except Exception as e:
            raise APIException('未查询到该用户')


